package com.suneee.store.service.impl;

import java.sql.Timestamp;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.suneee.base.util.ContextHelper;
import com.suneee.base.util.JsonUtil;
import com.suneee.channel.dao.ChannelDao;
import com.suneee.channel.entity.Channel;
import com.suneee.component.excel.ExcelUtil;
import com.suneee.context.page.Page;
import com.suneee.core.error.Assert;
import com.suneee.core.error.ErrorUtils;
import com.suneee.core.util.StringUtils;
import com.suneee.resources.ProductError;
import com.suneee.shop.dao.ShopDao;
import com.suneee.shop.entity.Shop;
import com.suneee.store.bean.CompareRecordBean;
import com.suneee.store.bean.ShopStockBean;
import com.suneee.store.bean.SyncTmallResultBean;
import com.suneee.store.bean.ViewShopStockDTO;
import com.suneee.store.bean.ViewShopStockRecordsDTO;
import com.suneee.store.bean.ViewStockRecordDTO;
import com.suneee.store.dao.ShopStockDao;
import com.suneee.store.dao.SkuDao;
import com.suneee.store.dao.StockDetailDao;
import com.suneee.store.dao.StockRecordDao;
import com.suneee.store.dao.ViewCompareRecordDetailDao;
import com.suneee.store.dao.ViewShopStockDao;
import com.suneee.store.dao.ViewShopStockRecordsDao;
import com.suneee.store.dao.ViewStockRecordDao;
import com.suneee.store.entity.ShopStock;
import com.suneee.store.entity.Sku;
import com.suneee.store.entity.StockDetail;
import com.suneee.store.entity.StockRecord;
import com.suneee.store.entity.ViewCompareRecordDetail;
import com.suneee.store.entity.ViewShopStock;
import com.suneee.store.entity.ViewShopStockRecords;
import com.suneee.store.entity.ViewStockRecord;
import com.suneee.store.extend.ComparePage;
import com.suneee.store.resources.StaticParam;
import com.suneee.store.service.IThirdPartyService;
import com.suneee.store.service.ProductService;
import com.suneee.store.service.ShopStockService;
import com.suneee.store.service.ThirdPartyFactory;
import com.suneee.web.bean.DownloadInfo;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.ItemsCustomGetRequest;
import com.taobao.api.request.SkusCustomGetRequest;
import com.taobao.api.response.ItemsCustomGetResponse;
import com.taobao.api.response.SkusCustomGetResponse;

@Service("api-shopStock")
public class ShopStockServiceImpl implements ShopStockService {
	
	private static final Logger log = LoggerFactory.getLogger(ShopStockServiceImpl.class);
	
	public static final String EXPORT_XLS = "/templates/product.compare.export.xls";

	@Autowired
	private ViewShopStockRecordsDao viewShopStockRecordsDao;
	
	@Autowired
	private ShopStockDao shopStockDao;
	
	@Autowired
	private ProductService productService;
	
	@Autowired
	private SkuDao skuDao;
	
	@Autowired
	private StockDetailDao stockDetailDao;
	
	@Autowired
	private ViewShopStockDao viewShopStockDao;
	
	@Autowired
	private ViewStockRecordDao viewStockRecordDao;
	
	@Autowired
	private ShopDao shopDao;
	
	@Autowired
	private StockRecordDao stockRecordDao;
	
	@Autowired
	private ViewCompareRecordDetailDao viewCompareRecordDetailDao;
	
	@Autowired
	private ChannelDao channelDao;
	
	@Override
	public Page<Map<String,Object>> getShopStockRecords(ViewShopStockRecordsDTO dto) {
		if(dto == null)
		{
			dto = new ViewShopStockRecordsDTO();
		}
		dto.setEnterpriseCode(ContextHelper.getCurrentLoginInfo()
				.getEnterprise().getEnterpriseCode());
		//return viewShopStockRecordsDao.mapListView(dto);
		DecimalFormat decimalFormat=new DecimalFormat("##0.00");
		Page<Map<String, Object>> list=viewShopStockRecordsDao.mapListView(dto);
		 if(list != null&&list.getItems().size()>0){
			 for (int i = 0; i < list.getItems().size(); i++) {
				 if(list.getItems().get(i).get("marketPrice")!=null)list.getItems().get(i).put("marketPrice", decimalFormat.format(Float.parseFloat(list.getItems().get(i).get("marketPrice").toString())));
				 
				 if(list.getItems().get(i).get("price")!=null)list.getItems().get(i).put("price", decimalFormat.format(Float.parseFloat(list.getItems().get(i).get("price").toString())));
			 }
		 }
		return list;
				
	}

	@Override
	@Transactional
	public List<SyncTmallResultBean> decreaseShopStocks(List<ViewShopStockRecordsDTO> dtoList,Integer operateStoreId,String remark,String stockType) {
		// TODO Auto-generated method stub
		Assert.notEmpty(dtoList, "操作对象");
		StockRecord record = this.createNewRecord(operateStoreId,remark,stockType);
		List<ViewShopStockRecordsDTO> successList = new ArrayList<>();
		List<SyncTmallResultBean> result = new ArrayList<>();
		for(ViewShopStockRecordsDTO dto : dtoList){
			//扣减外部商城库存
			if(!outShopDecreaseStocks(dto)){
				SyncTmallResultBean bean = new SyncTmallResultBean();
				bean.setTitle(String.valueOf(dto.getSkuId()));
				bean.setStatus(false);
				bean.setMessage("扣减外部商城库存失败！");
				result.add(bean);
				continue;
			}
			successList.add(dto);
		}
		if(!successList.isEmpty()){
			Map<Integer,List<ViewShopStockRecordsDTO>> map = new HashMap<>();
			for(ViewShopStockRecordsDTO dto : successList){
				if(map.get(dto.getShopId()) == null)
					map.put(dto.getShopId(), new ArrayList<>());
				map.get(dto.getShopId()).add(dto);
			}
			for(Integer shopId : map.keySet()){
				List<ViewShopStockRecordsDTO> temp = map.get(shopId);
				record.setOperateStoreId(shopId);//操作仓ID
				record.setStockDetailList(new ArrayList<>());
				for(ViewShopStockRecordsDTO dto : temp){
					//扣减店铺库存
					ShopStock shopStock = shopStockDao.selectByIdEnterpriseCode(dto.getStockId(), 
							ContextHelper.getCurrentLoginInfo().getEnterprise().getEnterpriseCode());
					shopStock.setStock(shopStock.getStock() - dto.getIncoming());
					shopStockDao.update(shopStock);
					//生成入库单数据
					StockDetail detail = this.createNewRecordDetail(dto);
					record.getStockDetailList().add(detail);
					Sku sku = skuDao.select(detail.getSkuId());
					sku.setStock(sku.getStock() + detail.getIncoming());
					skuDao.update(sku);
					SyncTmallResultBean bean = new SyncTmallResultBean();
					bean.setTitle(String.valueOf(dto.getSkuId()));
					bean.setStatus(true);
					bean.setMessage("操作成功！");
					result.add(bean);
				}
				record.setRelevantStoreId(StaticParam.VIRTUAL_WAREHOUSE);//虚拟总仓id
				
				
				record.setOperateChannelCode(StaticParam.VW_CHANNEL_CODE);//虚拟总仓渠道标识
				Shop shop = shopDao.select(shopId);
				Channel channel = channelDao.getChannelByChannelCode(shop.getChannelCode());
				if(channel != null){
					record.setChannelCode(channel.getChannelCode());
					record.setRelevantChannelCode(channel.getChannelCode());//关联仓库所属渠道
				}
					
				
				//生成店铺出库单
				productService.insertStockRecord(record,StaticParam.OUT_FLAG);
				//生成虚拟总仓入库单
				if(!stockType.equals(StaticParam.OUTSTORE_OUT_DAMAGE) && !stockType.equals(StaticParam.CREATE_ORDER_OUT)){
					
					record.setRecordType(StaticParam.V_STOCK_TYPE_IN);
					record.setStockType(StaticParam.IN_TYPE_FALLBACK);
					productService.insertStockRecord(record,StaticParam.IN_FLAG);
				}
			}	
		}
		return result;
	}

	private Boolean outShopDecreaseStocks(ViewShopStockRecordsDTO dto) {
		Shop shop = shopDao.get(dto.getShopId());
		String channelCode = shop.getChannelCode();
		IThirdPartyService client = null;
		if (StaticParam.TMALL_CODE.equalsIgnoreCase(channelCode)) {
			client = ThirdPartyFactory.getTmallClient();
		}

		if (null == client) {
			log.error("无效渠道编码");
			return false;
		}

		Map<String, String> publicParams = JsonUtil.parse(shop.getRuleInfo());
		publicParams.put("url", shop.getProxyURL());

		String enterpriseCode = ContextHelper.getCurrentLoginInfo().getEnterprise().getEnterpriseCode();
		ShopStock shopStock = shopStockDao.selectByIdEnterpriseCode(dto.getStockId(), enterpriseCode);

		Map<String, String> bizParams = JsonUtil.parse(shop.getRuleInfo());
		bizParams.put("numIid", shopStock.getChannelSpu());
		bizParams.put("outerId", String.valueOf(dto.getSkuId()));
		bizParams.put("quantity", String.valueOf(0 - dto.getIncoming()));
		try {
			boolean updateStatus = client.updateStock(publicParams, bizParams);
			return updateStatus;
		} catch (Exception e) {
			log.error("更新库存错误："+e);
			return false;
		}
	}
	
	
	private StockRecord createNewRecord(Integer operateStoreId,String remark,String stockType){
		StockRecord record = new StockRecord();
		record.setEnterpriseCode(ContextHelper.getCurrentLoginInfo()
				.getEnterprise().getEnterpriseCode());
		record.setRecordType(StaticParam.D_STOCK_TYPE_OUT);
		record.setStockType(stockType);
		record.setOperateStoreId(operateStoreId);
		record.setRelevantStoreId(StaticParam.VIRTUAL_WAREHOUSE);
		record.setRemark(remark);
		record.setCreateUserId(ContextHelper.getCurrentLoginInfo().getAdminId());
		record.setCreateTime(new Timestamp(System.currentTimeMillis()));
		return record;
	}
	
	private StockDetail createNewRecordDetail(ViewShopStockRecordsDTO dto){
		StockDetail detail = new StockDetail();
		detail.setSpuId(dto.getSpuId());
		detail.setSkuId(dto.getSkuId());
		detail.setIncoming(dto.getIncoming());
		detail.setPrice(dto.getPrice());
		return detail;
	}

	@Override
	@Transactional
	public List<SyncTmallResultBean> updatePrice(List<ViewShopStockRecordsDTO> dtoList, String remark) {
		// TODO Auto-generated method stub
		List<SyncTmallResultBean> result = new ArrayList<>();
		List<ViewShopStockRecordsDTO> successList = new ArrayList<>();
		for(ViewShopStockRecordsDTO dto : dtoList){
			if(this.updatePriceOutStore(dto))
				successList.add(dto);
			else{
				SyncTmallResultBean	bean = new SyncTmallResultBean();
				bean.setTitle(String.valueOf(dto.getSkuId()));
				bean.setStatus(false);
				bean.setMessage("同步外部商城价格失败！");
				result.add(bean);
			}
				
			
		}
		for(ViewShopStockRecordsDTO dto : successList){
			ShopStock shopStock = shopStockDao.select(dto.getStockId());
			shopStock.setPrice(dto.getPrice());
			shopStockDao.update(shopStock);
			SyncTmallResultBean	bean = new SyncTmallResultBean();
			bean.setTitle(String.valueOf(dto.getSkuId()));
			bean.setStatus(true);
			bean.setMessage("操作成功！");
			result.add(bean);
		}
		return result;
	}
	
	private Boolean updatePriceOutStore(ViewShopStockRecordsDTO dto) {
		Shop shop = shopDao.get(dto.getShopId());
		String channelCode = shop.getChannelCode();
		IThirdPartyService client = null;
		if (StaticParam.TMALL_CODE.equalsIgnoreCase(channelCode)) {
			client = ThirdPartyFactory.getTmallClient();
		}

		if (null == client) {
			log.error("无效渠道编码");
			return false;
		}

		Map<String, String> publicParams = JsonUtil.parse(shop.getRuleInfo());
		publicParams.put("url", shop.getProxyURL());

		String enterpriseCode = ContextHelper.getCurrentLoginInfo().getEnterprise().getEnterpriseCode();
		ShopStock shopStock = shopStockDao.selectByIdEnterpriseCode(dto.getStockId(), enterpriseCode);

		Map<String, String> bizParams = new HashMap<String, String>();
		bizParams.put("spuId", String.valueOf(shopStock.getSpuId()));
		bizParams.put("outerId", String.valueOf(dto.getSkuId()));
		bizParams.put("price", String.valueOf(dto.getPrice()));
		bizParams.put("itemId", shopStock.getChannelSpu());
		try {
			List<Float> priceList = client.getPriceList(publicParams, bizParams);
			if (null == priceList) {
				return false;
			}
			Collections.sort(priceList);

			Float minPrice = priceList.get(0);
			bizParams.put("minParice", String.valueOf(minPrice));

			boolean updatePrice = client.updateStorePrice(publicParams, bizParams);

			return updatePrice;

		} catch (Exception e) {
			log.error("更新价格错误："+e);
			return false;
		}
	}

	@Override
	public Page<ViewShopStockRecords> compareList(ViewShopStockRecordsDTO dto) {
		// TODO Auto-generated method stub
		if(dto == null)
			dto = new ViewShopStockRecordsDTO();
		dto.setEnterpriseCode(ContextHelper.getCurrentLoginInfo()
				.getEnterprise().getEnterpriseCode());
//		dto.setStatus(StaticParam.SYNC_STATUS_WAITTING);
//		List<StockDetail> list = stockDetailDao.selectListByRecordId(dto.getRecordId());
		List<Object> stockIdList = new ArrayList<>();
//		if(list != null && !list.isEmpty()){
//			for(StockDetail de : list)
//				stockIdList.add(de.getStockId());
//		}
		dto.setStockIdList(stockIdList);
		Page<ViewShopStockRecords> page = viewShopStockRecordsDao.listView(dto);	
		return page;
	}
	
	@Override
	@Transactional
	public List<SyncTmallResultBean> updateWaitingMatchSkus(List<ViewStockRecord> list) throws Exception{
		Assert.notEmpty(list, "操作对象");
		List<ShopStock> temp = new ArrayList<>();
		Integer relevantStoreId = null;
		List<SyncTmallResultBean> result = new ArrayList<>();
		String recordId = null;
		for(ViewStockRecord t : list){
			//得到单条待比对数据
			ViewStockRecord record = viewStockRecordDao.getRecordByRecordIdAndSkuId(t.getRecordId(), t.getSkuId());
			if(record.getStatus().equals("比对成功"))
				throw ErrorUtils.wrap(ProductError.THE_GOODS_HAVE_BEEN_COMPARED_TO_SUCCESS);
			
			relevantStoreId = record.getRelevantStoreId();
			if(recordId == null)
				recordId = t.getRecordId();
			ShopStock initShopStock = null;
			/**  查询店铺信息,如果没有店铺信息，则修改比对数据的状态为比对失败，返回错误信息到前端  */
			Shop shop  = shopDao.get(relevantStoreId);
			if(shop == null){
				StockDetail stockDetail = stockDetailDao.getDetailByRecordIdAndSkuId(t.getRecordId(), t.getSkuId());//查询待比对明细记录
				stockDetail.setStatus(StaticParam.SYNC_STATUS_FAIL);
				stockDetail.setFailReason("店铺不存在");
				stockDetailDao.update(stockDetail);
				this.createSyncResult(String.valueOf(stockDetail.getSkuId()), stockDetail, result);
				continue;
			}
			/** 如果店铺已经被禁用，则修改比对数据的状态为比对失败，返回错误信息到前端 */
			if(!shop.isEnabled() || !shop.getStatus().equals(Shop.USE)){
				StockDetail stockDetail = stockDetailDao.getDetailByRecordIdAndSkuId(t.getRecordId(), t.getSkuId());//查询待比对明细记录
				stockDetail.setStatus(StaticParam.SYNC_STATUS_FAIL);
				stockDetail.setFailReason("店铺已被禁用！");
				stockDetailDao.update(stockDetail);
				this.createSyncResult(String.valueOf(stockDetail.getSkuId()), stockDetail, result);
				continue;
			}
			IThirdPartyService client = null;
			if (StaticParam.TMALL_CODE.equalsIgnoreCase(shop.getChannelCode())) {
				client = ThirdPartyFactory.getTmallClient();
			}
			//转换连接信息
			Map<String,String> shopMap = JsonUtil.parse(shop.getRuleInfo());
			shopMap.put("url", shop.getProxyURL());
			
			StockDetail stockDetail = stockDetailDao.getDetailByRecordIdAndSkuId(t.getRecordId(), t.getSkuId());//查询待比对明细记录
			//查询是否比对过
			ShopStock shopStock = shopStockDao.getListBySkuSpu(record.getSpuId(), record.getSkuId(),
					ContextHelper.getCurrentLoginInfo().getEnterprise().getEnterpriseCode(),shop.getShopId());
			//初始化tmall SPU SKU
			if(shopStock == null ){//如果店铺仓不存在记录
				initShopStock = initShopStock(stockDetail,record, shop);
				shopMap.put("spuId", record.getSpuId().toString());
				shopMap.put("skuId", record.getSkuId().toString());
				String spuId = getTmallSpu(shopMap);//获取TmallSPU
				if(StringUtils.isNull(spuId)){
					stockDetail.setStatus(StaticParam.SYNC_STATUS_FAIL);
					stockDetail.setFailReason("查询天猫侧商品失败，请检查店铺对接信息");
					stockDetailDao.update(stockDetail);
					this.createSyncResult(String.valueOf(stockDetail.getSkuId()), stockDetail, result);
					continue;
				}
				if(StringUtils.isEmpty(spuId)){ //如果spu在tmall侧不存在
					//更新出入仓明细比对数据的状态
					stockDetail.setStatus(StaticParam.SYNC_STATUS_FAIL);
					stockDetail.setFailReason("商品SPU在天猫侧不存在");
					stockDetailDao.update(stockDetail);
					this.createSyncResult(String.valueOf(stockDetail.getSkuId()), stockDetail, result);
					continue;//抛出异常
				}
				String skuId = getTmallSku(shopMap);
				if(StringUtils.isEmpty(skuId)){ //如果sku在tmall侧不存在
					stockDetail.setStatus(StaticParam.SYNC_STATUS_FAIL);
					stockDetail.setFailReason("商品SKU在天猫侧不存在");
					stockDetailDao.update(stockDetail);
					this.createSyncResult(String.valueOf(stockDetail.getSkuId()), stockDetail, result);
					continue;
				}
				
				initShopStock.setChannelSpu(spuId);
				initShopStock.setChannelSku(skuId);
				
				shopMap.put("outerId", record.getSkuId().toString());
				//shopMap.put("price", record.getPrice().toString());
				shopMap.put("price", String.valueOf(stockDetail.getPrice()));
				shopMap.put("itemId", initShopStock.getChannelSpu());
				
				Map<String,String> paramMap = new HashMap<String, String>();
				paramMap.put("spuId", record.getSpuId().toString());
				paramMap.put("skuId", record.getSkuId().toString());
				paramMap.put("outerId", record.getSkuId().toString());
				paramMap.put("price", String.valueOf(stockDetail.getPrice()));
				paramMap.put("itemId", initShopStock.getChannelSpu());
				paramMap.put("numIid", initShopStock.getChannelSpu());
				Integer quantity = stockDetail.getIncoming() - (stockDetail.getFallback() == null ? 0:stockDetail.getFallback());
				paramMap.put("quantity", String.valueOf(quantity));
				
                boolean priceFlag = modifyPrice(shopMap,paramMap,client);//调用tmall价格接口
				if(!priceFlag){  //更新当前记录为对比失败
					stockDetail.setStatus(StaticParam.SYNC_STATUS_FAIL);
					stockDetail.setFailReason("更新价格失败");
					stockDetailDao.update(stockDetail);
					this.createSyncResult(String.valueOf(stockDetail.getSkuId()), stockDetail, result);
					continue;
				}
				boolean stockFlag = client.updateStock(shopMap, paramMap);//调用tmall库存接口
				if(!stockFlag) {
					stockDetail.setStatus(StaticParam.SYNC_STATUS_FAIL);
					stockDetail.setFailReason("更新库存失败");
					stockDetailDao.update(stockDetail);
					this.createSyncResult(String.valueOf(stockDetail.getSkuId()), stockDetail, result);
					continue;
				}
				//插入店铺仓库记录
				shopStockDao.insert(initShopStock);
				
				//修改入库单记录
				stockDetail.setStatus(StaticParam.SYNC_STATUS_SUCCESS);
				stockDetailDao.update(stockDetail);
				
				temp.add(initShopStock);//放入待插入的入库明细信息
				this.createSyncResult(String.valueOf(stockDetail.getSkuId()), stockDetail, result);		
			}else{
				shopMap.put("outerId", record.getSkuId().toString());
				//shopMap.put("price", record.getPrice().toString());
				shopMap.put("price", String.valueOf(stockDetail.getPrice()));
				shopMap.put("itemId", shopStock.getChannelSpu());
				
				
				Map<String,String> paramMap = new HashMap<String, String>();
				paramMap.put("spuId", record.getSpuId().toString());
				paramMap.put("skuId", record.getSkuId().toString());
				paramMap.put("outerId", record.getSkuId().toString());
				paramMap.put("price", String.valueOf(stockDetail.getPrice()));
				paramMap.put("itemId", shopStock.getChannelSpu());
				paramMap.put("numIid", shopStock.getChannelSpu());
				Integer quantity = stockDetail.getIncoming() - (stockDetail.getFallback() == null ? 0:stockDetail.getFallback());
				paramMap.put("quantity", String.valueOf(quantity));
				
				 boolean stockFlag = client.updateStock(shopMap, paramMap);
				 if(!stockFlag) {
					stockDetail.setStatus(StaticParam.SYNC_STATUS_FAIL);
					stockDetail.setFailReason("更新库存失败,请检查店铺对接信息或库存信息");
					stockDetailDao.update(stockDetail);
					this.createSyncResult(String.valueOf(stockDetail.getSkuId()), stockDetail, result);
					continue;
				 }
				//更新店铺仓库记录
				shopStock.setStock(quantity + shopStock.getStock());
				//shopStock.setPrice(record.getPrice());
				shopStockDao.update(shopStock);
				
				//修改总仓出库单记录的比对状态
				stockDetail.setStatus(StaticParam.SYNC_STATUS_SUCCESS);
				stockDetailDao.update(stockDetail);
				
				//入库单记录
				shopStock.setStock(quantity);
				temp.add(shopStock);
				this.createSyncResult(String.valueOf(stockDetail.getSkuId()), stockDetail, result);
			}
		}
		//生成店铺入库单
		StockRecord tt = null;
		if(recordId != null){
			tt = stockRecordDao.select(recordId);
		}
		StockRecord record = createStoreStockRecord(temp,StaticParam.D_STOCK_TYPE_IN,StaticParam.OUTSTORE_IN_V_ALLOCATION,tt == null?null:tt.getRemark());
		if(record != null){
			record.setRelevantStoreId(relevantStoreId);
			Shop shop = shopDao.get(relevantStoreId);
			record.setChannelCode(shop.getChannelCode());
			record.setOperateChannelCode(StaticParam.VW_CHANNEL_CODE);
			record.setRelevantChannelCode(shop.getChannelCode());
			productService.insertStockRecord(record, StaticParam.IN_FLAG);
		}
		return result;
	}
	
	private void createSyncResult(String recordId,StockDetail detail,List<SyncTmallResultBean> result){
		SyncTmallResultBean bean = new SyncTmallResultBean();
		bean.setTitle(recordId);
		if(!detail.getStatus().equals(StaticParam.SYNC_STATUS_SUCCESS)){
			bean.setStatus(false);
			bean.setMessage(detail.getFailReason());
		}
		else{
			bean.setStatus(true);
			bean.setMessage("比对成功！");
		}	
		result.add(bean);
	}
	
	public ShopStock initShopStock(StockDetail stockDetail, ViewStockRecord shopStockRecord,Shop shop){
		ShopStock shopStock = new ShopStock();
		shopStock.setShopId(shop.getShopId());
		shopStock.setSpuId(shopStockRecord.getSpuId());
		shopStock.setSkuId(shopStockRecord.getSkuId());
		shopStock.setWarningStock(0);
		//shopStock.setPrice(shopStockRecord.getPrice());
//		shopStock.setStock(shopStockRecord.getIncoming());
		shopStock.setStock(stockDetail.getIncoming());
		shopStock.setPrice(stockDetail.getPrice());
		Timestamp timestamp = new Timestamp(System.currentTimeMillis());
		shopStock.setCreateTime(timestamp);
		return shopStock;
	}
	
	public String getTmallSpu(Map<String,String> shopMap) throws Exception{
		//tmall接口查询对应的SPU
		TaobaoClient client = new DefaultTaobaoClient(shopMap.get("url"), shopMap.get("appKey"), shopMap.get("secret"));
		ItemsCustomGetRequest req = new ItemsCustomGetRequest();
		req.setOuterId(shopMap.get("spuId"));
		req.setFields("num_iid");
		ItemsCustomGetResponse rsp = client.execute(req, shopMap.get("appSession"));
		if(rsp.isSuccess()){
			ObjectMapper mapper = new ObjectMapper();
			JsonNode readTree = mapper.readTree(rsp.getBody().toString());
			String spuId = null;
			try{
				spuId= JsonUtil.getValueByFind(readTree,"num_iid");
			}
			catch(Exception e){
				spuId = null;
			}
			return spuId;
		}
		else{
//			throw ErrorUtils.wrap(ProductError.ENTERPRISE_NO_ROLE,rsp.getSubMsg() != null?rsp.getSubMsg():"获取外部商城spu编码失败！");
			return null;
		}
	}
	
	public String getTmallSku(Map<String,String> shopMap) throws Exception{
		//tmall接口查询对应的SKU
		TaobaoClient client = new DefaultTaobaoClient(shopMap.get("url"), shopMap.get("appKey"), shopMap.get("secret"));
		SkusCustomGetRequest req = new SkusCustomGetRequest();
		req.setOuterId(shopMap.get("skuId"));
		req.setFields("sku_id");
		SkusCustomGetResponse rsp = client.execute(req, shopMap.get("appSession"));
		if(rsp.isSuccess()){
			ObjectMapper mapper = new ObjectMapper();
			JsonNode readTree = mapper.readTree(rsp.getBody().toString());
			String skuId = null;
			try{
				skuId = JsonUtil.getValueByFind(readTree,"sku_id");
			}
			catch(Exception e){
				skuId = null;
			}
			return skuId;
		}
		else{
//			throw ErrorUtils.wrap(ProductError.ENTERPRISE_NO_ROLE,rsp.getSubMsg() != null?rsp.getSubMsg():"获取外部商城sku编码失败！");
			return null;
		}
	}
	
	public boolean modifyPrice(Map<String,String> pubMap,Map<String,String> paramMap,IThirdPartyService client) throws Exception{
		List<Float> priceList = client.getPriceList(pubMap,paramMap);
		if(null == priceList ){
			return false;
		}
		Collections.sort(priceList);
		
		Float minPrice = priceList.get(0);
		paramMap.put("minParice", String.valueOf(minPrice));
		
		boolean updatePrice = client.updateStorePrice(pubMap,paramMap);
		return updatePrice;
	}
	
	private StockRecord createStoreStockRecord(List<ShopStock> list,String recordType,String stockType,String relevantInfo){
		StockRecord record = new StockRecord();
		record.setRecordType(recordType);
		record.setStockType(stockType);
		record.setRemark(relevantInfo);
		record.setCreateUserId(ContextHelper.getCurrentLoginInfo().getAdminId());
		record.setCreateTime(new Timestamp(System.currentTimeMillis()));
		record.setOperateStoreId(StaticParam.VIRTUAL_WAREHOUSE);
		record.setStockDetailList(new ArrayList<>());
		record.setEnterpriseCode(ContextHelper.getCurrentLoginInfo().getEnterprise().getEnterpriseCode());
		if(list == null || list.isEmpty())
			return null;
		for(ShopStock ss : list){
			StockDetail detail = new StockDetail();
			detail.setSpuId(ss.getSpuId());
			detail.setSkuId(ss.getSkuId());
			detail.setIncoming(ss.getStock());
			detail.setPrice(ss.getPrice());
			detail.setStatus(StaticParam.SYNC_STATUS_SUCCESS);
			record.getStockDetailList().add(detail);
		}
		return record;
	}
	
	
	@Override
	@Transactional
	public void feedback(List<ViewShopStockRecordsDTO> dtoList, String remark) {
		Assert.notEmpty(dtoList, "操作对象");
		List<Sku> skuList = new ArrayList<>();
		Integer operateStore = null;
 
		for(ViewShopStockRecordsDTO dto : dtoList){
			ViewStockRecord record = viewStockRecordDao.getRecordByRecordIdAndSkuId(dto.getRecordId(), dto.getSkuId());
			StockDetail detail = stockDetailDao.select(record.getDetailId());
			if(detail.getStatus().equals(StaticParam.SYNC_STATUS_SUCCESS) 
					|| detail.getStatus().equals(StaticParam.SYNC_STATUS_FALLBACK))
				throw ErrorUtils.wrap(ProductError.ENTERPRISE_NO_ROLE,"只能对比对失败及待比对的商品回退！");
			if(detail.getIncoming() < dto.getIncoming())
				throw ErrorUtils.wrap(ProductError.ENTERPRISE_NO_ROLE,"回退数不能大于待同步库存！");
//			detail.setIncoming(detail.getIncoming() - dto.getIncoming());
			detail.setFallback((detail.getFallback() == null?0:detail.getFallback()) + dto.getIncoming());
			detail.setFailReason(remark);
			if(detail.getIncoming() - detail.getFallback() <= 0)
				detail.setStatus(StaticParam.SYNC_STATUS_FALLBACK);
			stockDetailDao.update(detail);
			Sku sku = skuDao.select(detail.getSkuId());
			sku.setStock(sku.getStock() + dto.getIncoming());
			sku.setAssignedStock(sku.getAssignedStock() - dto.getIncoming());
			sku.setTempStock(dto.getIncoming());
			skuDao.update(sku);
			skuList.add(sku);
			if(operateStore == null)
				operateStore = record.getRelevantStoreId();
		}
		//生成虚拟总仓入库记录
		productService.inStockNewRecord(skuList, StaticParam.IN_TYPE_FALLBACK, operateStore,remark);
	}

	@Override
	public DownloadInfo exportWaitingMatchSkus(List<ViewStockRecordDTO> params) {
		// TODO Auto-generated method stub
		List<ViewCompareRecordDetail> list = null;
		for(ViewStockRecordDTO dto : params){
			ViewCompareRecordDetail record = viewCompareRecordDetailDao.getRecordByRecordIdAndSkuId(dto.getRecordId(), dto.getSkuId());
			if(record != null){
				if(list == null)
					list = new ArrayList<>();
				list.add(record);
				record.setCategoryName(productService.getCategoryNames(record.getCategoryCode()));
			}
		}
		DownloadInfo downloadInfo = ExcelUtil.writeExcle(EXPORT_XLS, list, ExcelUtil.replaceTimestamp("product.compare"));
		return downloadInfo;
	}

	@Override
	public List<ShopStockBean> getListBySkuId(Integer skuId) {
		// TODO Auto-generated method stub
//		String enterpriseCode = ContextHelper.getCurrentLoginInfo().getEnterprise().getEnterpriseCode();
//		List<ShopStock> list = shopStockDao.getListBySkuId(skuId, enterpriseCode);
		List<Map<String, Object>> list =  stockDetailDao.getOutDetailBySkuId(skuId);
		if(list == null)
			return null;
		List<ShopStockBean> beanList = new ArrayList<>();
		for(Map<String, Object> ss : list){
			ShopStockBean bean = new ShopStockBean();
			bean.setSkuId((Integer)ss.get("sku_id"));
			bean.setStock((Integer)ss.get("stock"));
			bean.setCreateTime(new Timestamp(((Date)ss.get("create_time")).getTime()));
			bean.setShopName((String)ss.get("shop_name"));
			beanList.add(bean);
		}
		return beanList;
	}

	@Override
	public Page<Map<String, Object>> getShopStocks(ViewShopStockDTO dto) {
		// TODO Auto-generated method stub
		if(dto == null)
			dto = new ViewShopStockDTO();
		dto.setEnterpriseCode(ContextHelper.getCurrentLoginInfo().getEnterprise().getEnterpriseCode());
		Page<Map<String, Object>> list = viewShopStockDao.listView(dto);

		//start
		DecimalFormat decimalFormat=new DecimalFormat("##0.00");
		if(list != null&&list.getItems().size()>0){
			for (int i = 0; i < list.getItems().size(); i++) {

				list.getItems().get(i).put("categoryName",productService.getCategoryNames(list.getItems().get(i).get("categoryCode").toString()));
				if(list.getItems().get(i).get("marketPrice")!=null)list.getItems().get(i).put("marketPrice", decimalFormat.format(Float.parseFloat(list.getItems().get(i).get("marketPrice").toString())));
				if(list.getItems().get(i).get("price")!=null)list.getItems().get(i).put("price", decimalFormat.format(Float.parseFloat(list.getItems().get(i).get("price").toString())));
			}
		}
		return list;
		//end


	}

	@Override
	public List<ComparePage<ViewCompareRecordDetail>> getCompareList() {
		// TODO Auto-generated method stub
		ViewStockRecordDTO dto = new ViewStockRecordDTO();
		dto.setRecordType(StaticParam.V_STOCK_TYPE_OUT);
		dto.setOperateStoreId(StaticParam.VIRTUAL_WAREHOUSE);
		dto.setEnterpriseCode(ContextHelper.getCurrentLoginInfo().getEnterprise().getEnterpriseCode());
		List<String> recordIdList = viewStockRecordDao.getRecordIdList(dto);
		if(recordIdList == null || recordIdList.isEmpty())
			return null;
		List<ComparePage<ViewCompareRecordDetail>> list = new ArrayList<>();
		for(String recordId : recordIdList){
			dto.setRecordId(recordId);
			Page<ViewCompareRecordDetail> page = viewCompareRecordDetailDao.getPageByRecordId(dto);
			ComparePage<ViewCompareRecordDetail> cPage = null;
			if(page != null && page.getItems() != null && !page.getItems().isEmpty()){
				cPage = this.wrapNewComparePage(cPage, page, dto);
				list.add(cPage);
			}	
		}
		return list;
	}

	@Override
	public List<CompareRecordBean> getCompareRecordList() {
		// TODO Auto-generated method stub
		ViewStockRecordDTO dto = new ViewStockRecordDTO();
		dto.setRecordType(StaticParam.V_STOCK_TYPE_OUT);
		dto.setOperateStoreId(StaticParam.VIRTUAL_WAREHOUSE);
		dto.setEnterpriseCode(ContextHelper.getCurrentLoginInfo().getEnterprise().getEnterpriseCode());
		List<String> recordIdList = viewStockRecordDao.getRecordIdList(dto);
		if(recordIdList == null || recordIdList.isEmpty())
			return null;
		CompareRecordBean bean = null;
		List<CompareRecordBean> compareList = new ArrayList<>();
		for(String recordId : recordIdList){
			dto.setRecordId(recordId);
			List<ViewCompareRecordDetail> list = viewCompareRecordDetailDao.getListByRecordId(dto);
			if(list != null && !list.isEmpty()){
				for(ViewCompareRecordDetail detail : list){
					detail.setCategoryName(productService.getCategoryNames(detail.getCategoryCode()));
				}
				bean = this.wrapNewCompareBean(bean, list, dto);
				compareList.add(bean);
			}
		}
		return compareList;
	}

	@Override
	public ComparePage<ViewCompareRecordDetail> getComparePage(ViewStockRecordDTO dto) {
		// TODO Auto-generated method stub
		Assert.notNull(dto, "操作对象");
		Assert.notNull(dto.getRecordId(), "出库单号");
		Page<ViewCompareRecordDetail> page = viewCompareRecordDetailDao.getPageByRecordId(dto);
		ComparePage<ViewCompareRecordDetail> cPage = null;
		if(page != null && page.getItems() != null && !page.getItems().isEmpty()){
			cPage = this.wrapNewComparePage(cPage, page, dto);
		}
		return cPage;
	}
	
	/**
	 * 把Page对象包装成ComparePage对象
	 * @param cPage 目标对象
	 * @param page 源对象
	 * @param dto 查询参数
	 * @return
	 */
	private ComparePage<ViewCompareRecordDetail> wrapNewComparePage(
			ComparePage<ViewCompareRecordDetail> cPage,
			Page<ViewCompareRecordDetail> page,
			ViewStockRecordDTO dto){
		cPage = new ComparePage<ViewCompareRecordDetail>();
		cPage.setItems(page.getItems());
		cPage.setOffset(page.getOffset());
		cPage.setPageNumber(page.getPageNumber());
		cPage.setPageSize(page.getPageSize());
		cPage.setTotalItems(page.getTotalItems());
		cPage.setTotalWaiting(viewCompareRecordDetailDao.getTotalWaitingByRecordId(dto));
		cPage.setTotalFail(viewCompareRecordDetailDao.getTotalFailByRecordId(dto));
		StockRecord record = stockRecordDao.select(dto.getRecordId());
		cPage.setCreateTime(record == null?null:record.getCreateTime());
		return cPage;
	}
	
	private CompareRecordBean wrapNewCompareBean(CompareRecordBean bean,
			List<ViewCompareRecordDetail> list,
			ViewStockRecordDTO dto){
		bean = new CompareRecordBean();
		bean.setItems(list);
		bean.setTotal(list == null || list.isEmpty() ? 0 : list.size());
		bean.setTotalWaiting(viewCompareRecordDetailDao.getTotalWaitingByRecordId(dto));
		bean.setTotalFail(viewCompareRecordDetailDao.getTotalFailByRecordId(dto));
		StockRecord record = stockRecordDao.select(dto.getRecordId());
		bean.setCreateTime(record == null?null:record.getCreateTime());
		return bean;
	}

	@Override
	public Page<CompareRecordBean> getCompareRecordPage(ViewStockRecordDTO dto) {
		if(dto == null)
			dto = new ViewStockRecordDTO();
		dto.setRecordType(StaticParam.V_STOCK_TYPE_OUT);
		dto.setOperateStoreId(StaticParam.VIRTUAL_WAREHOUSE);
		dto.setStockType(StaticParam.OUT_TYPE_ALLOCATION);//调拨出库
		dto.setEnterpriseCode(ContextHelper.getCurrentLoginInfo().getEnterprise().getEnterpriseCode());
		Page<Map<String, Object>> recordIdPage = viewStockRecordDao.getRecordIdPage(dto);
		Page<CompareRecordBean> page = new Page<>();
		page.setOffset(recordIdPage.getOffset());
		page.setPageNumber(recordIdPage.getPageNumber());
		page.setPageSize(recordIdPage.getPageSize());
		page.setTotalItems(recordIdPage.getTotalItems());
		page.setTotalPages(recordIdPage.getTotalPages());
		if(recordIdPage == null || recordIdPage.getItems() == null || recordIdPage.getItems().isEmpty())
			return page;
		CompareRecordBean bean = null;
		List<CompareRecordBean> compareList = new ArrayList<>();
		DecimalFormat decimalFormat=new DecimalFormat("##0.00");
		for(Map<String,Object> recordId : recordIdPage.getItems()){
			dto.setRecordId((String)recordId.get("record_id"));
			List<ViewCompareRecordDetail> list = viewCompareRecordDetailDao.getListByRecordId(dto);
			if(list != null && !list.isEmpty()){
				for(ViewCompareRecordDetail detail : list){
					if(detail.getAdvicePrice()!=null)detail.setAdvicePriceSt(decimalFormat.format(Float.parseFloat(detail.getAdvicePrice().toString())));
					if(detail.getMarketPrice()!=null)detail.setMarketPriceSt(decimalFormat.format(Float.parseFloat(detail.getMarketPrice().toString())));
				}
				bean = this.wrapNewCompareBean(bean, list, dto);
				compareList.add(bean);
			}
		}
		page.setItems(compareList);
		return page;
	}
	
}
